package com.atguigu.tingshu.user.strategy.impl;

import cn.hutool.core.collection.CollUtil;
import com.atguigu.tingshu.album.AlbumFeignClient;
import com.atguigu.tingshu.model.album.TrackInfo;
import com.atguigu.tingshu.model.user.UserPaidTrack;
import com.atguigu.tingshu.user.service.UserPaidTrackService;
import com.atguigu.tingshu.user.strategy.PaidRecordStrategy;
import com.atguigu.tingshu.vo.user.UserPaidRecordVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: atguigu
 * @create: 2025-03-25 09:08
 */
@Slf4j
@Component("1002") //默认Bean对象ID=类名(首首字母小写)
public class TrackPaidRecordStrategy implements PaidRecordStrategy {

    @Autowired
    private UserPaidTrackService userPaidTrackService;

    @Autowired
    private AlbumFeignClient albumFeignClient;

    /**
     * 处理声音虚拟物品发货逻辑
     * @param userPaidRecordVo
     */
    @Override
    public void handlerPaidRecord(UserPaidRecordVo userPaidRecordVo) {
        log.info("处理声音虚拟物品发货逻辑");
        //2.1 判断订单编号是否已处理
        Long count = userPaidTrackService.count(
                new LambdaQueryWrapper<UserPaidTrack>()
                        .eq(UserPaidTrack::getOrderNo, userPaidRecordVo.getOrderNo())
        );
        if (count > 0) {
            return;
        }
        //2.2 未处理 构建声音购买记录（可能存在多条） 完成新增
        List<Long> trackIdList = userPaidRecordVo.getItemIdList();
        if (CollUtil.isNotEmpty(trackIdList)) {
            //2.2.1 根据声音ID远程调用"专辑服务"查询声音信息
            TrackInfo trackInfo = albumFeignClient.getTrackInfo(trackIdList.get(0)).getData();
            //2.2.2 批量保存声音购买记录
            List<UserPaidTrack> userPaidTrackList = trackIdList
                    .stream()
                    .map(trackId -> {
                        UserPaidTrack userPaidTrack = new UserPaidTrack();
                        userPaidTrack.setOrderNo(userPaidRecordVo.getOrderNo());
                        userPaidTrack.setUserId(userPaidRecordVo.getUserId());
                        userPaidTrack.setAlbumId(trackInfo.getAlbumId());
                        userPaidTrack.setTrackId(trackId);
                        return userPaidTrack;
                    }).collect(Collectors.toList());
            userPaidTrackService.saveBatch(userPaidTrackList);
        }
    }
}
